from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from init.mysql import engine

Base = declarative_base()


class StockCash(Base):
    __tablename__ = 'stock_cash'
    id = Column(Integer, primary_key=True, autoincrement=True)
    code = Column(String(6))
    date = Column(String(10))
    jyin = Column(String(20))
    jyout = Column(String(20))
    jyfinal = Column(String(20))
    tzin = Column(String(20))
    tzout = Column(String(20))
    tzfinal = Column(String(20))
    czin = Column(String(20))
    czout = Column(String(20))
    czfinal = Column(String(20))
    hl = Column(String(20))
    cashinc = Column(String(20))
    cashs = Column(String(20))
    cashe = Column(String(20))

    def __init__(self, code, date, jyin, jyout, jyfinal, tzin, tzout, tzfinal, czin, czout, czfinal, hl, cashinc, cashs,
                 cashe):
        self.code = code
        self.date = date
        self.jyin = jyin
        self.jyout = jyout
        self.jyfinal = jyfinal
        self.tzin = tzin
        self.tzout = tzout
        self.tzfinal = tzfinal
        self.czin = czin
        self.czout = czout
        self.czfinal = czfinal
        self.hl = hl
        self.cashinc = cashinc
        self.cashs = cashs
        self.cashe = cashe

    @staticmethod
    def insert_or_update(code, data_list):
        session = sessionmaker(bind=engine)()
        for data in data_list:
            stock_cash = session.query(StockCash).filter_by(code=code, date=data['date']).first()
            if stock_cash:
                stock_cash.date = data['date']
                stock_cash.jyin = data['jyin']
                stock_cash.jyout = data['jyout']
                stock_cash.jyfinal = data['jyfinal']
                stock_cash.tzin = data['tzin']
                stock_cash.tzout = data['tzout']
                stock_cash.tzfinal = data['tzfinal']
                stock_cash.czin = data['czin']
                stock_cash.czout = data['czout']
                stock_cash.czfinal = data['czfinal']
                stock_cash.hl = data['hl']
                stock_cash.cashinc = data['cashinc']
                stock_cash.cashs = data['cashs']
                stock_cash.cashe = data['cashe']

            else:
                session.add(StockCash(code=code, date=data['date'], jyin=data['jyin'], jyout=data['jyout'],
                                      jyfinal=data['jyfinal'], tzin=data['tzin'], tzout=data['tzout'],
                                      tzfinal=data['tzfinal'], czin=data['czin'], czout=data['czout'],
                                      czfinal=data['czfinal'], hl=data['hl'], cashinc=data['cashinc'],
                                      cashs=data['cashs'], cashe=data['cashe']))
        session.commit()


Base.metadata.create_all(engine)
